import 'dart:convert';

import '../../../../core/exceptions/auth_exception.dart';
import '../models/user.dart';
import 'package:http/http.dart' as http;

class CustomBackendAuthRepository {
  final http.Client _client;
  final String _baseUrl;

  CustomBackendAuthRepository(this._client, this._baseUrl);

  User? _currentUser;

  User? get currentUser => _currentUser;

  Stream<User?> authStateChanges() async* {
    // 你可以根据需求实现监听用户状态变化的逻辑
    // 尝试从本地存储加载当前用户信息
    // final prefs = await SharedPreferences.getInstance();
    // final userJson = prefs.getString('currentUser');
    // if (userJson != null) {
    //   _currentUser = User.fromJson(jsonDecode(userJson));
    // }
    yield _currentUser;
  }

  Future<User> signInWithEmailAndPassword(String email, String password) async {
    // final response = await _client.post(
    //   Uri.parse('$_baseUrl/auth/login'),
    //   body: jsonEncode({'email': email, 'password': password}),
    // );

    // if (response.statusCode == 200) {
    //   _currentUser = User.fromJson(jsonDecode(response.body));

    //   // 将用户信息保存到本地
    //   // final prefs = await SharedPreferences.getInstance();
    //   // prefs.setString('currentUser', jsonEncode(_currentUser));

    //   return _currentUser!;
    // } else {
    //   throw _parseError(response);
    // }
    // 这里我们使用 mock 数据来模拟返回的用户信息，而不再发请求到后端
    await Future.delayed(const Duration(seconds: 1)); // 模拟网络延迟

    // 假设我们总是成功登录，返回一个 mock 用户
    final mockUser = User(
      uid: 'mock-uid-12345',
      email: email,
      displayName: 'Mock User',
      createdAt: DateTime.now(),
      lastLoginAt: DateTime.now(),
    );

    // 模拟成功的返回
    _currentUser = mockUser;
    return _currentUser!;
  }

  AuthException _parseError(http.Response response) {
    final error = jsonDecode(response.body);
    switch (error['code']) {
      case 401:
        return InvalidCredentialsException();
      default:
        return GenericAuthException(message: error['message']);
    }
  }

  Future<void> sendPasswordResetEmail(String email) async {
    // 实现密码重置的逻辑
    throw UnimplementedError();
  }

  Future<User> signInAnonymously() async {
    // 实现匿名登录的逻辑
    throw UnimplementedError();
  }

  Future<User> signInWithPhone(String phone, String smsCode) async {
    // 实现手机号登录的逻辑
    throw UnimplementedError();
  }

  Future<User> signInWithWeChat() async {
    // 实现微信登录的逻辑
    throw UnimplementedError();
  }

  Future<void> signOut() async {
    // 清除本地存储的用户信息
    // final prefs = await SharedPreferences.getInstance();
    // 实现退出登录的逻辑
    _currentUser = null;
  }

  Future<User> updateProfile(User updates) async {
    // 实现更新用户资料的逻辑
    throw UnimplementedError();
  }
}
